package com.brave.mvvm.mvvmhelper.utils

import android.graphics.Color
import androidx.annotation.ColorInt
import androidx.annotation.FloatRange
import androidx.annotation.IntRange
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.Utils
import com.brave.mvvm.mvvmhelper.base.CommonApp
import kotlin.math.max
import kotlin.math.min

/**
 * ***author*** ：brave tou
 *
 * ***data***   : 2021/9/1 15:32
 *
 * ***desc***   : Color工具
 */

/**
 * hex颜色转颜色值
 */
@JvmOverloads
@ColorInt
fun Any?.hexToColor(@ColorInt defaultColor: Int = Color.WHITE): Int {
    return try {
        Color.parseColor("$this")
    } catch (e: Exception) {
        e.printStackTrace()
        defaultColor
    }
}

/**
 * 颜色资源ID转颜色值
 */
@JvmOverloads
@ColorInt
fun Int.resIdToColor(@ColorInt defaultColor: Int = Color.WHITE): Int {
    return try {
        val context = CommonApp.default.applicationContext
            ?: Utils.getApp().applicationContext
        ContextCompat.getColor(context, this)
    } catch (e: Exception) {
        e.printStackTrace()
        defaultColor
    }
}

/**
 * 修改颜色透明度
 * @param alpha 透明度 0～255
 */
fun Int.changeAlpha(@IntRange(from = 0, to = 255) alpha: Int): Int {
    val color = this
    val red = Color.red(color)
    val green = Color.green(color)
    val blue = Color.blue(color)
    return Color.argb(max(0, min(255, alpha)), red, green, blue)
}

/**
 * 修改颜色透明度
 * @param alpha 透明度 0f～1f
 */
@ColorInt
fun Int.changeAlpha(@FloatRange(from = 0.0, to = 1.0) alpha: Float): Int {
    return changeAlpha((alpha * 255f).toInt())
}

/**
 * 修改颜色透明度
 * @param alpha 透明度 0.0～1.0
 */
@ColorInt
fun Int.changeAlpha(@FloatRange(from = 0.0, to = 1.0) alpha: Double): Int {
    return changeAlpha((alpha * 255f).toInt())
}